package com.acxiom.bsh.controller;

import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.acxiom.bsh.cache.NickNameCache;
import com.acxiom.bsh.constants.CommonConstant;
import com.acxiom.bsh.pojo.KeyValue;
import com.acxiom.bsh.request.ApiAdjustPointRequest;
import com.acxiom.bsh.request.CommonApiRequest;
import com.acxiom.bsh.request.MemberRequest;
import com.acxiom.bsh.request.WarrantyExtRequest;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.util.DateUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping("/api")
public class ApiController {

	@Autowired
	ApiService apiService;

	@Value("${tp.api.event.collection.code}")
	private String eventCodeCollection;

	@Value("${tp.api.event.collection.memo}")
	private String eventMemoCollection;

	@Value("${tp.api.event.follow.code}")
	private String eventCodeFollow;

	@Value("${tp.api.event.follow.memo}")
	private String eventMemoFollow;

	@RequestMapping(value = "/name")
	public @ResponseBody ApiResponse getMemberName(HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		String name = null;
		if (NickNameCache.get(nickName) != null) {
			ApiResponse response = new ApiResponse();
			response.setData(NickNameCache.get(nickName));
			return response;
		}
		CommonApiRequest request = new CommonApiRequest();
		request.setMix_taobaoId(nickName);
		ApiResponse response = apiService.post("convert/taobaoId/toCT", request);
		if (response != null && response.getData() != null) {
			@SuppressWarnings("rawtypes")
			Map<?, ?> map = (Map) response.getData();
			if (map.get("taobaoId") != null) {
				name = map.get("taobaoId").toString();
			}
			NickNameCache.put(nickName, name);
		}
		if (response != null) {
			response.setData(name);
		}

		return response;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/member")
	public @ResponseBody ApiResponse getCustomer(HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}

		ApiResponse response = apiService.get("member", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", nickName));
		if (response.getData() != null) {
			Map<String, Object> jsonMap = (Map<String, Object>) JSONObject.toJSON(response.getData());
			JSONArray jsonArray = (JSONArray) jsonMap.get("points");
			JSONObject json =  JSONObject.parseObject(jsonArray.get(0).toString());
			List<Map<String, Object>> list = (List<Map<String, Object>>) jsonMap.get("points");
			list.get(0).put("totalActivePoints","100");
			jsonMap.put("points", list);
			if (jsonMap.get("address1") == null || jsonMap.get("address2") == null || jsonMap.get("address3") == null) {
				jsonMap.put("address1", null);
				jsonMap.put("address2", null);
				jsonMap.put("address3", null);
				jsonMap.put("address4", null);
				//jsonMap.put("points", "["+json+"]");
			}
			Object targetObject = JSONObject.toJSON(jsonMap);
			response.setData(targetObject);
		}

		return response;
	}


	@RequestMapping(value = "/member/img")
	public @ResponseBody ApiResponse getCustomerImg(HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		@SuppressWarnings("deprecation")
		String mixNick = URLDecoder.decode(nickName);

		String picurl = apiService.getUserAvatarByMixNick(mixNick);
		ApiResponse response = new ApiResponse();
		response.setData(picurl);
		return response;
	}

	@RequestMapping(value = "/member", method = RequestMethod.PUT)
	public @ResponseBody ApiResponse updateCustomer(HttpSession session, @RequestBody MemberRequest body) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		body.setMix_taobaoId(nickName);
		body.setiSN(System.currentTimeMillis());
		String path = "member";
		return apiService.post(path, body);
	}

	@RequestMapping(value = "/point/detail")
	public @ResponseBody ApiResponse getCustomerPoints(@RequestParam(value = "pageIndex", required = true) final int pageIndex, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		ApiResponse response = apiService.get("point/detail", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", nickName), new KeyValue("dateFrom", DateUtils.getPreviousDayString(-365)), new KeyValue("dateEnd", DateUtils.currentDate()), new KeyValue("pageIndex", Integer.toString(pageIndex)));
		return response;
	}

	@RequestMapping(value = "/purchase")
	public @ResponseBody ApiResponse getCustomerPurchases(@RequestParam(value = "pageIndex", required = true) final int pageIndex, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		return apiService.get("purchase", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", nickName), new KeyValue("dateFrom", DateUtils.getPreviousDayString(-365)), new KeyValue("dateEnd", DateUtils.currentDate()), new KeyValue("pageIndex", Integer.toString(pageIndex)));
	}

	@RequestMapping(value = "/product")
	public @ResponseBody ApiResponse getCustomerProducts(@RequestParam(value = "pageIndex", required = true) final int pageIndex, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		return apiService.get("product", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", nickName), new KeyValue("pageIndex", Integer.toString(pageIndex)));
	}

	@RequestMapping(value = "/repair")
	public @ResponseBody ApiResponse getProductRepairs(@RequestParam(value = "pageIndex", required = true) final int pageIndex, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		return apiService.get("benefits/warrantyExt", new KeyValue("iSN", Long.toString(System.currentTimeMillis())), new KeyValue("mix_taobaoId", nickName), new KeyValue("pageIndex", Integer.toString(pageIndex)));
	}

	@RequestMapping(value = "/warranty/{id}", method = RequestMethod.PUT)
	public @ResponseBody ApiResponse benefits(@PathVariable(value = "id", required = true) final int id, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		WarrantyExtRequest request = new WarrantyExtRequest();
		request.setMix_taobaoId(nickName);
		request.setLcs_id(id);
		return apiService.post("benefits/warrantyExt", request);
	}

	@RequestMapping(value = "/register/{id}", method = RequestMethod.PUT)
	public @ResponseBody ApiResponse register(@PathVariable(value = "id", required = true) final int id, HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		WarrantyExtRequest request = new WarrantyExtRequest();
		request.setMix_taobaoId(nickName);
		request.setLcs_id(id);
		return apiService.post("benefits/productReg", request);
	}

	@RequestMapping(value = "/collection")
	public @ResponseBody ApiResponse getCollection(HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		String path = "point";
		ApiAdjustPointRequest request = new ApiAdjustPointRequest();
		request.setMix_taobaoId(nickName);
		request.setiSN(System.currentTimeMillis());
		request.setEventCode(eventCodeCollection);
		request.setEventMemo(eventMemoCollection);
		return apiService.post(path, request);
	}

	@RequestMapping(value = "/follow")
	public @ResponseBody ApiResponse getFollow(HttpSession session) {
		String nickName = getNickName(session);
		if (nickName == null) {
			return null;
		}
		String path = "point";
		ApiAdjustPointRequest request = new ApiAdjustPointRequest();
		request.setMix_taobaoId(nickName);
		request.setiSN(System.currentTimeMillis());
		request.setEventCode(eventCodeFollow);
		request.setEventMemo(eventMemoFollow);
		return apiService.post(path, request);
	}

	private String getNickName(HttpSession session) {
		Object obj = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		String nickName = null;
		if (obj != null) {
			nickName = obj.toString();
		}
		return nickName;
	}
}
